package com.wise.ftp.utils;

import com.wise.ftp.domain.Ftp;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.util.StringUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FtpUtil {
    private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);
    private static FTPClient ftpClient;

    /**
     * 获取连接并切换到工作目录
     * @param ftp
     * @return
     */
    public static boolean connectFtp(Ftp ftp){
        boolean status = false;
        ftpClient = new FTPClient();
        ftpClient.setConnectTimeout(30000);
        //由于我是用的win10搭建的ftp服务器，所以字符编码格式为GBK
        ftpClient.setControlEncoding("GBK");
        try {
            if (StringUtils.isEmpty(ftp.getPort())) {
                ftpClient.connect(ftp.getIpAddr(), 21);
            } else {
                ftpClient.connect(ftp.getIpAddr(),ftp.getPort());
            }
            ftpClient.login(ftp.getAccount(), ftp.getPwd());
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            int replyCode = ftpClient.getReplyCode();
            if (FTPReply.isPositiveCompletion(replyCode)){
                status = true;
                ftpClient.changeWorkingDirectory(ftp.getPath());
            } else {
                ftpClient.disconnect();
            }
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
            e.printStackTrace();
        }
        return status;
    }

    /**
     * 关闭ftp连接
     */
    public static void closeFtp(){
        if (ftpClient != null && ftpClient.isConnected()){
            try {
                ftpClient.logout();
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error(e.getMessage(),e);
                e.printStackTrace();
            }
        }
    }

    /**
     * 上传文件(上传目录为时间日期)
     * @param f
     */
    public static void upload(File f){
        try {
            if (f.isFile()){
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                String targetDir = "/L-"+sdf.format(new Date());
                if (!ftpClient.changeWorkingDirectory(targetDir)){
                    ftpClient.makeDirectory(targetDir);
                    ftpClient.changeWorkingDirectory(targetDir);
                }
                File path = new File(f.getPath());
                FileInputStream fis = new FileInputStream(path);
                //new String(f.getName().getBytes("GBK"),"iso-8859-1")
                ftpClient.storeFile(f.getName(), fis);
                ftpClient.changeToParentDirectory();
                fis.close();
                logger.info("文件:{} 上传成功!  访问目录:{}",f.getName(),targetDir);
            }
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
            e.printStackTrace();
        }
    }

    /**
     * 下载文件
     */
    public static void downloadFile(String remoteFile,String localPath){
        try {
            FileOutputStream out = new FileOutputStream(new File(localPath));
            ftpClient.retrieveFile(remoteFile,out);
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Ftp ftp = new Ftp();
        ftp.setIpAddr("192.168.3.31");
        ftp.setPort(21);
        ftp.setAccount("lintest");
        ftp.setPwd("123456");
        ftp.setPath("/");
        File file = new File("G:\\download\\Spring源码深度解析.pdf");
        if (connectFtp(ftp)){
            upload(file);
        }
        System.out.println("文件已经上传至ftp服务器");
        downloadFile("/L-20190412/Spring源码深度解析.pdf","E:/ftpdowntest.pdf");
    }
}
